package jt.classic.app.dms.timer;

import java.io.File;
import java.sql.Connection;
import java.util.Timer;
import java.util.TimerTask;

import jt.classic.app.dms.scanner.DMSFtpFileArray;
import jt.classic.app.dms.scanner.DMSFtpFileScanner;
import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;


/**
 * DMS 用户ftp上传文件保存器
 *
 * @author mido
 *
 */
public class DMSFtpFileSaveTimer {
    private Timer timer = new Timer();
    private long delay = 5000;
    private long period = 10000;

    public DMSFtpFileSaveTimer() {
    }

    public void runTask() {
        System.out.println(
            "system message: DMS ftp-file-saver timer task is running...");
        timer.schedule(new MyTask(), this.delay, this.period);
    }

    public void stopTask() {
        System.out.println(
            "system message: DMS ftp-file-saver timer task is cancelled...");
        timer.cancel();
    }

    private class MyTask extends TimerTask {
        public MyTask() {
        }

        public void run() {
            Connection conn = null;
            DMSFtpFileArray dffa = DMSFtpFileArray.getInstance();

            if (!dffa.isEmpty()) {
                Object[] obj = null;

                try {
                    SystemDataSource ds = SystemDataSource.getInstance();
                    conn = ds.getConnection();

                    obj = new Object[] { dffa.get()[0], dffa.get()[1] };

                    dffa.remove();

                    DMSFtpFileScanner scanner = new DMSFtpFileScanner(conn);
                    scanner.autoSave((File) obj[1], (IUser) obj[0]);

                    conn.commit();

                    if (dffa.isEmpty()) {
                        dffa.clearMap();
                    }
                } catch (Exception ex) {
                    dffa.push((File) obj[1], (IUser) obj[0]);

                    ISystem.catchException("DMS ftp-file-saver error.", ex);

                    try {
                        conn.rollback();
                    } catch (Exception ex1) {
                        ISystem.catchException("DMS ftp-file-saver error.", ex1);
                    }
                } finally {
                    SystemDataSource.closeConnection(conn);
                }
            }
        }
    }
}
